package com.lht.femalecat.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

/**
 * @Author:骆宏图
 * @CreateDate: 14:47 2018/7/26.
 * @Description:
 * @Modified By:
 */
public class MultiplexerTimeServer implements Runnable {


    private Selector selector;

    private ServerSocketChannel serveChannel;

    /**
     * 首次见 volatile 运用
     */
    private volatile boolean stop;

    public MultiplexerTimeServer(int port) {

        try {
            selector = Selector.open();
            serveChannel = ServerSocketChannel.open();
            serveChannel.configureBlocking(false);
            serveChannel.bind(new InetSocketAddress("127.0.0.1", port));

            serveChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("The time server is start in port:" + port);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    public void stop() {
        this.stop = true;
    }


    @Override
    public void run() {
        while (!stop) {
            try {
                selector.select(1000);//阻塞  1000 毫秒      如果 0 则是一直阻塞
                Set<SelectionKey> selectionKeySet = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeySet.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();//删除事件

                    handleInput(selectionKey);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    private void handleInput(SelectionKey key) throws IOException {
        //valid
        if (key.isValid()) {
            if (key.isAcceptable()) {
                ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                SocketChannel socketChannel = serverSocketChannel.accept();
                socketChannel.configureBlocking(false);
                socketChannel.register(selector, SelectionKey.OP_READ);
            }
            if (key.isReadable()) {
                SocketChannel channel = (SocketChannel) key.channel();
                ByteBuffer reader = ByteBuffer.allocate(1024);
                int readerBytes = channel.read(reader);
                if (readerBytes > 0) {
                    reader.flip();
                    byte[] bytes = new byte[reader.remaining()];
                    reader.get(bytes);
                    String body = new String(bytes, "UTF-8");
                    System.out.println("The time server receive order:" + body);
                    String currentTime = "Query Time Order".equals(body) ? new Date(System.currentTimeMillis()).toString() : "Bad Order";
                    doWrite(channel, currentTime);
                } else if (readerBytes < 0) {
                    key.channel();//取消事件
                    channel.close();
                } else {
                    //读到0字节，忽略
                }
            }
        }
    }

    private void doWrite(SocketChannel channel, String response) throws IOException {
        if (response != null && response.trim().length() > 0) {
            byte[] bytes = response.getBytes();
            ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
            byteBuffer.put(bytes);
            byteBuffer.flip();
            channel.write(byteBuffer);
        }
    }
}
